<template>
  <div class="address-search">
    <base-dist
      v-model="distValue"
      :placeholder="placeholder"
      @input="handleCitySelectorChange"
      :showOneLine="true"
      :no-default-country="noDefaultCountry"
      :module="module"
    />
  </div>
</template>

<script>
import { defineComponent, reactive, watch, toRefs } from 'vue';
import i18n from '@src/locales';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()
export default defineComponent({
  name: 'address-search',
  props: {
    placeholder: {
      type: String,
      default: i18n.t('common.placeholder.selectAddress'),
    },
    value: {
      type: Object,
      default() {
        let value = {
          /**
           * value值必须包含以下值:
           * province: String,
           * city: String,
           * dist: String,
           * address: String
           *
           * 以下值可选：
           * latitude： [String,Number],
           * longitude: [String,Number],
           * addressType: Number
           */
        };

        return {};
      },
    },
    noDefaultCountry: {
      type: Boolean,
      default: false
    },
    // 模块
    module: {
      type: String,
      default: '',
    },
  },
  emits: ['update'],
  setup(props, { emit }) {
    let state = reactive({
      distValue: {}
    })

    watch(() => props.value, (newValue) => {
      if (newValue) {
        const { country = '', province, city, dist, street } = newValue || {};
        state.distValue = {
          country,
          province,
          city,
          dist,
          ...(street && { street })
        }
      } else {
        state.distValue = {}
      }
    }, { deep: true, immediate: true })

    function handleCitySelectorChange(val) {
      updateValue(val);
    }

    function updateValue(newValue) {
      // 工单客户关联字段清除位置信息时候不调用update
      emit('update', newValue);
    }

    return {
      ...toRefs(state),
      internationalGray,
      handleCitySelectorChange,
      updateValue,
    };
  },
});
</script>
